import React, { Component } from "react";
import { connect } from "react-redux";
import "./AuthenticatePay.scss";
import { Toast, InputItem } from "antd-mobile";
import { setUserType } from "../../../../Redux/Action/credit/AuthenticationA";
import yhTools from "../../../../tools/yh";
import { ThemeLife } from "../../../../tools/theme";
import MainLayout from "../../../../component/mainLayout/mainLayout";
import { InterfaceG } from "../../../../config/Config";

class AuthenticatePay extends Component {
	constructor(props) {
		super(props);
		this.state = {
			hasError: false,
			phoneValue: "",
			selectFlag: true,
			timeText: "120秒后重发",
			time: 120,
			yzmValue: "",
			data: {},
			fromType: ""
		};
		this.timer = null;
		this.timer1 = null;
		this.isOpen = true;
	}

	componentDidMount() {
		let data = JSON.parse(this.props.match.params.data);
		let pageParams = data.pageParams;
		this.h = document.body.clientHeight;
		this.countdown();
		this.setState({
			orderNo: data.orderNo,
			pageParams,
			data,
			fromType: pageParams.fromType
		});
	}

	componentWillUnmount() {
		clearInterval(this.timer);
	}

	onErrorClick = () => {
		if (this.state.hasError) {
			Toast.info("请输入正确的手机号码");
		}
	};

	onChange = phoneValue => {
		if (phoneValue.replace(/\s/g, "").length < 11) {
			this.setState({
				hasError: true
			});
		} else {
			this.setState({
				hasError: false
			});
		}
		this.setState({
			phoneValue
		});
	};

	//获取验证码
	getYzm() {
		if (!this.isOpen) {
			return false;
		}

		const _this = this;
		this.timer1 && clearTimeout(this.timer1);
		this.timer1 = setTimeout(() => {
			if (_this.props.match.params.data.fromType == "XHD") {
				//好借
				_this.getVerifyCode();
			} else {
				//小辉付
				_this.getXHFVerifyCode();
			}
		}, 1000);
	}

	//倒计时
	countdown() {
		this.isOpen = false;
		const _this = this;
		let { time } = this.state;
		this.timer = setInterval(() => {
			if (time < 1) {
				clearInterval(_this.timer);
				_this.isOpen = true;
				_this.setState({
					time: 120,
					timeText: "重新发送"
				});
			} else {
				time--;
				_this.setState({
					time,
					timeText: `${time}秒后重发`
				});
			}
		}, 1000);
	}

	//协议签约重获取验证码接口
	getVerifyCode() {
		const urlParams = this.state.data;
		const params = {
			url: InterfaceG.repeatGetVerifyCode,
			params: {
				bankCode: urlParams.bankCode //银行账户key
			},
			_alertShow: false
		};
		Toast.loading("正在提交中...", 100, () => {});
		yhTools
			.request(params)
			.then(res => {
				Toast.hide();
				const data = res.data;
				if (res.code === "0") {
					this.countdown();
					this.setState({
						VerifyCode: data,
						orderNo: data.orderNo
					});
				} else {
					Toast.info(res.message, 2);
				}
			})
			.catch(() => {
				Toast.hide();
			});
	}

	//小辉付协议签约重获取验证码接口
	getXHFVerifyCode() {
		const urlParams = this.state.data;
		const params = {
			url: `/payAuth/getVeryCode/1`,
			params: {
				bank_code: urlParams.bankCode, //银行账户key
				billNo: urlParams.billNo,
				amount: urlParams.amount //还款金额
			},
			_alertShow: false
		};
		Toast.loading("正在提交中...", 100, () => {});
		yhTools
			.request(params)
			.then(res => {
				Toast.hide();
				const data = res.data;
				if (res.code === "0") {
					this.setState({
						orderNo: data.orderNo
					});
					this.countdown();
				} else {
					Toast.info(res.message, 2);
				}
			})
			.catch(() => {
				Toast.hide();
			});
	}

	changeyzm(yzmValue) {
		this.setState({
			yzmValue
		});
	}

	//下一步
	nextTep() {
		const { yzmValue } = this.state;
		const _this = this;
		this.timer1 && clearTimeout(this.timer1);
		this.timer1 = setTimeout(() => {
			if (!yzmValue) {
				Toast.info("请输入验证码");
				return false;
			}
			if (yzmValue.length < 6) {
				Toast.info("请输入正确的验证码");
				return false;
			}
			if (_this.state.data.fromType == "XHD") {
				//好借
				_this.paySign();
			} else {
				//小辉付
				_this.xHFPaySign();
			}
		}, 1000);
	}

	//签约确认接口
	paySign() {
		const _this = this;
		const { yzmValue } = this.state;
		const params = {
			url: InterfaceG.signConfirm,
			params: {
				verifyCode: yzmValue,
				orderNo: this.state.orderNo
			},
			_alertShow: false
		};
		Toast.loading("正在提交中...", 100, () => {});
		yhTools
			.request(params)
			.then(res => {
				Toast.hide();
				if (res.code == "0") {
					_this.props.history.push({
						pathname: `/backPay`,
						state: {
							...res.data,
							..._this.state.data,
							pageParams: _this.state.pageParams
						}
					});
				} else {
					Toast.info(res.message, 2);
				}
			})
			.catch(() => {
				Toast.hide();
			});
	}

	//小辉付签约确认接口
	xHFPaySign() {
		const _this = this;
		const { yzmValue } = this.state;
		const urlParams = this.state.data;
		console.log(urlParams);
		const params = {
			url: `/payAuth/paySign/1`,
			params: {
				custcd: urlParams.custcd,
				account_name: urlParams.account_name,
				card_no: urlParams.card_no,
				bank_no: urlParams.bank_no,
				id_type: urlParams.id_type,
				id_no: urlParams.id_no,
				user_id: urlParams.user_id,
				orderNo: this.state.orderNo,
				billNo: urlParams.billNo,
				bank_mobile: urlParams.bankMobile,
				verifyCode: yzmValue,
				amount: urlParams.amount, // 还款金额
				repayMark: urlParams.repayMark, //如果为提前还款，需要加此参数
				unAccountAmount: urlParams.unAccountAmount,
				unRepayAmount: urlParams.unRepayAmount
			},
			_alertShow: false
		};
		Toast.loading("正在提交中...", 100, () => {});
		yhTools
			.request(params)
			.then(res => {
				Toast.hide();
				const data = res.data;
				if (res.code === "0") {
					_this.props.history.push({
						pathname: `/backPay`,
						state: {
							...data,
							...urlParams,
							custcd: urlParams.custcd,
							amount: urlParams.amount, // 还款金额
							billNo: urlParams.billNo,
							sucessPhoneNo: res.data.bank_mobile_new,
							pageParams: _this.state.pageParams,
							repayMark: urlParams.repayMark,
							unAccountAmount: urlParams.unAccountAmount,
							unRepayAmount: urlParams.unRepayAmount
						}
					});
				} else {
					Toast.info(res.message, 2);
				}
			})
			.catch(() => {
				Toast.hide();
			});
	}

	//跳转协议页面
	gotoAgreetext() {
		this.props.history.push("/agreementoflianyintong");
	}

	render() {
		const { fromType } = this.state;
		let goBackPath = "";
		if (fromType === "XHD") {
			goBackPath = `/repaymentMoney/${JSON.stringify(this.state.pageParams)}`;
		} else {
			goBackPath = `/xhfRepaymentPage/${JSON.stringify(this.state.pageParams)}`;
		}
		const headerParams = {
			header: {
				title: "认证支付"
			},
			history: this.props.history,
			cacheLifecycles: this.props.cacheLifecycles,
			loadStatus: this.state.loadStatus // （ '0'：数据加载中，'1'：加载完成，'2'：加载失败）
		};
		const { timeText } = this.state;
		let urlParams = this.state.data;
		return (
			<MainLayout pageParams={headerParams}>
				<div className="authenticatePay">
					<div className="card">
						<p className="card-l">
							<span className="card-l-name">卡号:</span>
							{urlParams.cardNo
								? yhTools.handelInfo(urlParams.cardNo, 3, 4)
								: ""}
						</p>
						<div className="card-r">
							<p className="card-name">
								<span className="card-l-name"></span>
								{urlParams.bankName}
							</p>
						</div>
					</div>
					<ul className="info">
						{/* <li>
                            <p className="info-l">
                                身份证
                            </p>
                            <div className="info-r">
                                <p>{urlParams.idNo}</p>
                            </div>
                        </li> */}
					</ul>
					<ul
						className={ThemeLife.switch(
							"info info-input lifeinfo",
							"info info-input"
						)}
					>
						<li>
							<p className="info-l">姓名</p>
							<div className="info-r">
								<p>
									{urlParams.accountName
										? yhTools.handelInfo(urlParams.accountName, 0, 1)
										: ""}
								</p>
							</div>
						</li>
						<li>
							<p className="info-l">预留手机号</p>
							<div className="info-r phone">
								<p>
									{urlParams.bankMobile
										? yhTools.handelInfo(urlParams.bankMobile, 3, 4)
										: ""}
								</p>
							</div>
						</li>
						<li className="yzm-box" ref="zym">
							<InputItem
								maxLength={6}
								type="number"
								placeholder="请输入验证码"
								onChange={this.changeyzm.bind(this)}
								value={this.state.yzmValue}
							>
								验证码
							</InputItem>
							<div className="info-yzm" onClick={this.getYzm.bind(this)}>
								{timeText}
							</div>
						</li>
					</ul>
					<div className="agree">
						<span style={{ color: "#999999" }}>查看</span>{" "}
						<span
							onClick={this.gotoAgreetext.bind(this)}
							style={{ color: "#302e2f" }}
						>
							《连连银通银行卡支付服务协议》
						</span>
					</div>
					<div
						className={this.state.selectFlag ? "btn-common" : "btn-common"}
						onClick={this.nextTep.bind(this)}
					>
						同意协议并支付
					</div>
				</div>
			</MainLayout>
		);
	}
}

function mapStateToProps(state) {
	return state;
}

function mapDispatchToProps(dispatch) {
	return {
		_setUserType: options => {
			dispatch(setUserType(options));
		}
	};
}

const AuthenticatePayPage = connect(
	mapStateToProps,
	mapDispatchToProps
)(AuthenticatePay);
export default AuthenticatePayPage;
